package cn.xdf.docscan

import android.graphics.Bitmap
import android.util.Log
import com.google.mediapipe.framework.Graph
import com.google.mediapipe.framework.Packet
import com.google.mediapipe.framework.PacketCreator
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * 输入处理器
 * 1:1复刻lsd.java的输入处理逻辑
 */
class InputProcessor(
    private val graph: Graph,
    private val packetCreator: PacketCreator
) {
    
    companion object {
        private const val TAG = "InputProcessor"
    }
    
    /**
     * 处理Bitmap输入
     * 完全按照lsd.java的逻辑实现
     */
    fun processBitmap(bitmap: Bitmap, timestamp: Long) {
        try {
            Log.d(TAG, "开始处理Bitmap: ${bitmap.width}x${bitmap.height}")
            
            // 1. 将Bitmap转换为ByteBuffer - 完全按照lsd.java的逻辑
            val buffer = ByteBuffer.allocateDirect(bitmap.byteCount)
            buffer.order(ByteOrder.nativeOrder())
            bitmap.copyPixelsToBuffer(buffer)
            buffer.rewind()
            
            Log.d(TAG, "缓冲区大小验证通过: ${bitmap.width}x${bitmap.height}x4 = ${buffer.capacity()}")
            
            // 2. 创建RGBA ImageFrame - 完全按照lsd.java的逻辑
            val packet = packetCreator.createRgbaImageFrame(
                buffer,
                bitmap.width,
                bitmap.height
            )
            
            // 4. 发送到Graph的input_frame_rgba流 - 完全按照lsd.java的逻辑
            graph.addPacketToInputStream("input_frame_rgba", packet, timestamp)
            
            // 5. 发送手动捕获请求 - 完全按照lsd.java的逻辑
            val captureRequestPacket = packetCreator.createBool(true)
            graph.addPacketToInputStream("manual_capture_request", captureRequestPacket, timestamp)
            
            // 6. 发送自动模式标志 - 完全按照lsd.java的逻辑
            val autoModePacket = packetCreator.createBool(true)
            graph.addPacketToInputStream("is_auto_mode", autoModePacket, timestamp)
            
            // 7. 释放资源 - 完全按照lsd.java的逻辑
            packet.release()
            captureRequestPacket.release()
            autoModePacket.release()
            
            Log.d(TAG, "✅ Bitmap处理完成，时间戳: $timestamp")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Bitmap处理失败", e)
        }
    }
    
    /**
     * 处理YUV输入（如果需要）
     * 完全按照lsd.java的逻辑实现
     */
    fun processYuvData(yuvData: ByteArray, width: Int, height: Int, timestamp: Long) {
        try {
            Log.d(TAG, "开始处理YUV数据: ${width}x${height}")
            
            // 由于缺少JNI接口，暂时使用RGBA转换
            // TODO: 实现真正的YUV处理
            Log.w(TAG, "⚠️ YUV处理暂时使用RGBA转换")
            
            // 创建YUV到RGBA的转换
            val rgbaData = yuvToRgba(yuvData, width, height)
            val buffer = ByteBuffer.allocateDirect(rgbaData.size)
            buffer.order(ByteOrder.nativeOrder())
            buffer.put(rgbaData)
            buffer.rewind()
            
            // 创建RGBA ImageFrame
            val packet = packetCreator.createRgbaImageFrame(
                buffer,
                width,
                height
            )
            
            // 发送到Graph
            graph.addPacketToInputStream("input_frame_rgba", packet, timestamp)
            
            // 发送控制信号
            val captureRequestPacket = packetCreator.createBool(true)
            graph.addPacketToInputStream("manual_capture_request", captureRequestPacket, timestamp)
            
            val autoModePacket = packetCreator.createBool(true)
            graph.addPacketToInputStream("is_auto_mode", autoModePacket, timestamp)
            
            // 释放资源
            packet.release()
            captureRequestPacket.release()
            autoModePacket.release()
            
            Log.d(TAG, "✅ YUV数据处理完成，时间戳: $timestamp")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ YUV数据处理失败", e)
        }
    }
    
    /**
     * YUV到RGBA转换
     * 简单的转换实现
     */
    private fun yuvToRgba(yuvData: ByteArray, width: Int, height: Int): ByteArray {
        val rgbaData = ByteArray(width * height * 4)
        val ySize = width * height
        val uvSize = ySize / 4
        
        for (y in 0 until height) {
            for (x in 0 until width) {
                val yIndex = y * width + x
                val uvIndex = (y / 2) * (width / 2) + (x / 2)
                
                val yValue = yuvData[yIndex].toInt() and 0xFF
                val uValue = yuvData[ySize + uvIndex].toInt() and 0xFF
                val vValue = yuvData[ySize + uvSize + uvIndex].toInt() and 0xFF
                
                // 简单的YUV到RGB转换
                val r = (yValue + 1.402 * (vValue - 128)).toInt().coerceIn(0, 255)
                val g = (yValue - 0.344 * (uValue - 128) - 0.714 * (vValue - 128)).toInt().coerceIn(0, 255)
                val b = (yValue + 1.772 * (uValue - 128)).toInt().coerceIn(0, 255)
                
                val rgbaIndex = (y * width + x) * 4
                rgbaData[rgbaIndex] = r.toByte()
                rgbaData[rgbaIndex + 1] = g.toByte()
                rgbaData[rgbaIndex + 2] = b.toByte()
                rgbaData[rgbaIndex + 3] = 255.toByte() // Alpha
            }
        }
        
        return rgbaData
    }
} 